package com.jxw.update;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.exoplayer2.C;
import com.jxw.launcher.AppInfo;
import com.jxw.launcher.MyApp;
import com.jxw.launcher.R;
import com.jxw.launcher.util.Logger;
import com.jxw.launcher.util.ReceiverUtil;
import com.jxw.launcher.util.Util;
import com.zzj.filedownloader.download.DownLoadListener;
import com.zzj.filedownloader.download.DownLoadManager;
import com.zzj.filedownloader.download.TaskInfo;
import com.zzj.filedownloader.download.dbcontrol.FileHelper;
import com.zzj.filedownloader.download.dbcontrol.bean.SQLDownLoadInfo;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/* loaded from: classes.dex */
public class Fragment1 extends Fragment {
    private static final String URL1 = Util.API_HOST + "/api/jxwota/apk/check?apkIsbn=zndzgkptv5&version=5.0";
    private OtaAdapter mOtaAdapter;
    private View mView;
    SparseArray<Button> mViewHolderArray;
    private ListView otaListView;
    ImageView tips;
    private List<AppInfo> updateList;
    private Handler mHandler = new Handler() { // from class: com.jxw.update.Fragment1.1
        @Override // android.os.Handler
        public void handleMessage(Message message) {
            int i = message.what;
            if (i != 0) {
                if (i != 1) {
                    return;
                }
                if (Fragment1.this.updateList.size() > 0) {
                    Fragment1.this.otaListView.setVisibility(0);
                    Fragment1.this.mOtaAdapter.notifyDataSetChanged();
                    Fragment1.this.tips.setVisibility(8);
                    return;
                }
                Fragment1.this.otaListView.setVisibility(8);
                Fragment1.this.tips.setVisibility(0);
            } else if (Fragment1.this.updateList.size() > 0) {
                Fragment1.this.otaListView.setVisibility(0);
                Fragment1.this.mOtaAdapter.notifyDataSetChanged();
                Log.d("zzj", "mOtaAdapter:" + Fragment1.this.mOtaAdapter.getCount());
                Fragment1.this.tips.setVisibility(8);
            } else {
                Fragment1.this.otaListView.setVisibility(8);
                Fragment1.this.tips.setVisibility(0);
            }
        }
    };
    private BroadcastReceiver recer = new BroadcastReceiver() { // from class: com.jxw.update.Fragment1.2
        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            if ("android.intent.action.PACKAGE_ADDED".equals(intent.getAction())) {
                String schemeSpecificPart = intent.getData().getSchemeSpecificPart();
                Log.d("zzj", "getOtaData=" + schemeSpecificPart);
                Fragment1.this.getOtaData(schemeSpecificPart);
            }
        }
    };
    private BroadcastReceiver networkReceiver = new BroadcastReceiver() { // from class: com.jxw.update.Fragment1.3
        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            NetworkInfo activeNetworkInfo;
            if (ReceiverUtil.ACTION_CONNECTIVITY_ACTION.equals(intent.getAction()) && (activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo()) != null && activeNetworkInfo.isConnected()) {
                Log.d("zzj", "networkReceiver=" + activeNetworkInfo.getType());
                Fragment1.this.checkUpdate();
            }
        }
    };

    /* JADX INFO: Access modifiers changed from: private */
    public void getOtaData(String str) {
        synchronized (this.updateList) {
            for (AppInfo appInfo : this.updateList) {
                if (appInfo.packageName.equals(str)) {
                    this.updateList.remove(appInfo);
                    this.mHandler.sendEmptyMessage(0);
                    return;
                }
            }
        }
    }

    @Override // android.support.v4.app.Fragment
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        this.mView = layoutInflater.inflate(R.layout.fragment_1, viewGroup, false);
        this.otaListView = (ListView) this.mView.findViewById(R.id.ota_list);
        this.tips = (ImageView) this.mView.findViewById(R.id.tips);
        this.updateList = new ArrayList();
        this.mOtaAdapter = new OtaAdapter();
        this.otaListView.setAdapter((ListAdapter) this.mOtaAdapter);
        this.mViewHolderArray = new SparseArray<>();
        getContext().registerReceiver(this.networkReceiver, new IntentFilter(ReceiverUtil.ACTION_CONNECTIVITY_ACTION));
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
        intentFilter.addDataScheme("package");
        getContext().registerReceiver(this.recer, intentFilter);
        return this.mView;
    }

    @Override // android.support.v4.app.Fragment
    public void onDestroyView() {
        super.onDestroyView();
        getContext().unregisterReceiver(this.networkReceiver);
        getContext().unregisterReceiver(this.recer);
    }

    @Override // android.support.v4.app.Fragment
    public void onHiddenChanged(boolean z) {
        super.onHiddenChanged(z);
    }

    public int getVersionName(String str) throws Exception {
        return MyApp.getInstance().getPackageManager().getPackageInfo(str, 0).versionCode;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void checkUpdate() {
        new OkHttpClient().newCall(new Request.Builder().url(URL1).build()).enqueue(new Callback() { // from class: com.jxw.update.Fragment1.4
            @Override // okhttp3.Callback
            public void onFailure(Call call, IOException iOException) {
                Log.d("zzj", "onFailure=" + iOException.getMessage());
            }

            @Override // okhttp3.Callback
            public void onResponse(Call call, Response response) throws IOException {
                Fragment1.this.getOtaData(response);
            }
        });
    }

    /* JADX INFO: Access modifiers changed from: private */
    public synchronized void getOtaData(Response response) throws IOException {
        Log.d("zzj", "onResponse=" + response);
        if (response.isSuccessful()) {
            String string = response.body().string();
            Log.d("zzj", "json=" + string);
            synchronized (this.updateList) {
                try {
                    this.updateList.clear();
                    JSONArray jSONArray = new JSONObject(string).getJSONArray("data");
                    PackageManager packageManager = MyApp.getInstance().getPackageManager();
                    for (int i = 0; i < jSONArray.length(); i++) {
                        JSONObject optJSONObject = jSONArray.optJSONObject(i);
                        String optString = optJSONObject.optString("packageName");
                        String optString2 = optJSONObject.optString("fileName");
                        String optString3 = optJSONObject.optString(IjkMediaPlayer.OnNativeInvokeListener.ARG_URL);
                        int optInt = optJSONObject.optInt("versionCode");
                        String printSize = Util.getPrintSize(optJSONObject.optLong("fileSize"));
                        try {
                            PackageInfo packageInfo = packageManager.getPackageInfo(optString, 0);
                            int i2 = packageInfo.versionCode;
                            Log.d("zzj", optString + ":update:" + optInt + "--" + i2);
                            if (optInt > i2) {
                                AppInfo appInfo = new AppInfo();
                                appInfo.packageName = optString;
                                appInfo.appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
                                appInfo.versionCode = optInt;
                                appInfo.localVer2 = printSize;
                                appInfo.apkName = optString2;
                                appInfo.appIcon = packageInfo.applicationInfo.loadIcon(packageManager);
                                appInfo.url = optString3;
                                this.updateList.add(appInfo);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    this.mHandler.sendEmptyMessage(1);
                } catch (JSONException e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* loaded from: classes.dex */
    public class OtaAdapter extends BaseAdapter {
        Dialog alertDialog = null;
        private DownLoadManager downLoadManager = new DownLoadManager(MyApp.getInstance());

        /* renamed from: tv  reason: collision with root package name */
        TextView f6tv;

        /* JADX INFO: Access modifiers changed from: private */
        public void showDownloadingDialog(String str, String str2, Drawable drawable) {
        }

        @Override // android.widget.Adapter
        public long getItemId(int i) {
            return i;
        }

        public OtaAdapter() {
            this.downLoadManager.setAllTaskListener(new DownloadManagerListener());
        }

        @Override // android.widget.Adapter
        public int getCount() {
            return Fragment1.this.updateList.size();
        }

        @Override // android.widget.Adapter
        public Object getItem(int i) {
            return Fragment1.this.updateList.get(i);
        }

        @Override // android.widget.Adapter
        public View getView(int i, View view, ViewGroup viewGroup) {
            View view2;
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view2 = LayoutInflater.from(Fragment1.this.getContext()).inflate(R.layout.activity_ota, (ViewGroup) null);
                holder.aapIcon = (ImageView) view2.findViewById(R.id.aapIcon);
                holder.appName = (TextView) view2.findViewById(R.id.aapName);
                holder.localVersion = (TextView) view2.findViewById(R.id.current_version);
                holder.remoteVersion = (TextView) view2.findViewById(R.id.remote_version);
                holder.update_btn = (Button) view2.findViewById(R.id.update);
                view2.setTag(holder);
            } else {
                view2 = view;
                holder = (Holder) view.getTag();
            }
            final AppInfo appInfo = (AppInfo) Fragment1.this.updateList.get(i);
            holder.aapIcon.setBackground(appInfo.appIcon);
            holder.appName.setText(appInfo.appName);
            TextView textView = holder.localVersion;
            textView.setText("" + appInfo.versionCode);
            TextView textView2 = holder.remoteVersion;
            textView2.setText("" + appInfo.localVer2);
            Fragment1.this.mViewHolderArray.put(appInfo.apkName.hashCode(), holder.update_btn);
            holder.update_btn.setOnClickListener(new View.OnClickListener() { // from class: com.jxw.update.Fragment1.OtaAdapter.1
                @Override // android.view.View.OnClickListener
                public void onClick(View view3) {
                    String str = FileHelper.baseFilePath + appInfo.apkName;
                    PackageInfo packageArchiveInfo = Fragment1.this.getContext().getPackageManager().getPackageArchiveInfo(str, 1);
                    Log.d("zzj", "archiveInfo:" + packageArchiveInfo);
                    if (packageArchiveInfo == null || appInfo.versionCode > packageArchiveInfo.versionCode || !appInfo.packageName.equals(packageArchiveInfo.packageName)) {
                        TaskInfo taskInfo = OtaAdapter.this.downLoadManager.getTaskInfo(appInfo.apkName);
                        Log.d("zzj", "taskInfo:" + taskInfo);
                        if (taskInfo != null) {
                            Log.d("zzj", "isOnDownloading:" + taskInfo.isOnDownloading());
                            if (!taskInfo.isOnDownloading()) {
                                OtaAdapter.this.downLoadManager.startTask(appInfo.apkName);
                            }
                            OtaAdapter.this.showDownloadingDialog(appInfo.apkName, appInfo.appName, appInfo.appIcon);
                            return;
                        }
                        OtaAdapter.this.downInstallApk(appInfo.apkName, appInfo.url, appInfo.appName, appInfo.appIcon);
                        return;
                    }
                    Fragment1.this.installApp(new File(str), Fragment1.this.getContext());
                }
            });
            return view2;
        }

        public void downInstallApk(String str, String str2, String str3, Drawable drawable) {
            try {
                File file = new File(FileHelper.getTempDirPath() + str);
                if (file.exists()) {
                    Logger logger = Logger.getLogger();
                    logger.d("deleteTask=" + file.getAbsolutePath());
                    file.delete();
                }
                File file2 = new File(FileHelper.getTempDirPath() + str.replace(".apk", ""));
                if (file2.exists()) {
                    Logger logger2 = Logger.getLogger();
                    logger2.d("deleteTask=" + file2.getAbsolutePath());
                    file2.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.downLoadManager.setSupportBreakpoint(true);
            DownLoadManager downLoadManager = this.downLoadManager;
            String replace = str.replace(".apk", "");
            downLoadManager.addTask(str, str2, replace, FileHelper.baseFilePath + str);
            this.downLoadManager.startTask(str);
            showDownloadingDialog(str, str3, drawable);
        }

        /* loaded from: classes.dex */
        private class DownloadManagerListener implements DownLoadListener {
            private DownloadManagerListener() {
            }

            @Override // com.zzj.filedownloader.download.DownLoadListener
            public void onStart(SQLDownLoadInfo sQLDownLoadInfo) {
                Logger logger = Logger.getLogger();
                logger.d("onStart,name=" + sQLDownLoadInfo.getTaskID());
            }

            @Override // com.zzj.filedownloader.download.DownLoadListener
            public void onProgress(SQLDownLoadInfo sQLDownLoadInfo, boolean z) {
                TaskInfo taskInfo = OtaAdapter.this.downLoadManager.getTaskInfo(sQLDownLoadInfo.getTaskID());
                if (taskInfo != null) {
                    taskInfo.setDownFileSize(sQLDownLoadInfo.getDownloadSize());
                    taskInfo.setFileSize(sQLDownLoadInfo.getFileSize());
                    taskInfo.setOnDownloading(true);
                    Button button = Fragment1.this.mViewHolderArray.get(sQLDownLoadInfo.getTaskID().hashCode());
                    if (button != null) {
                        button.setText(taskInfo.getProgress() + "%");
                    }
                }
                Logger logger = Logger.getLogger();
                logger.d("onProgress,name=" + sQLDownLoadInfo.getTaskID() + ",size=" + sQLDownLoadInfo.getDownloadSize());
            }

            @Override // com.zzj.filedownloader.download.DownLoadListener
            public void onStop(SQLDownLoadInfo sQLDownLoadInfo, boolean z) {
                Logger logger = Logger.getLogger();
                logger.d("onStop,name=" + sQLDownLoadInfo.getTaskID());
                Button button = Fragment1.this.mViewHolderArray.get(sQLDownLoadInfo.getTaskID().hashCode());
                if (button != null) {
                    button.setText("");
                }
            }

            @Override // com.zzj.filedownloader.download.DownLoadListener
            public void onSuccess(SQLDownLoadInfo sQLDownLoadInfo) {
                Logger logger = Logger.getLogger();
                logger.d("onSuccess,name=" + sQLDownLoadInfo.getTaskID());
                Button button = Fragment1.this.mViewHolderArray.get(sQLDownLoadInfo.getTaskID().hashCode());
                if (button != null) {
                    button.setText("完成");
                }
                Fragment1.this.installApp(new File(sQLDownLoadInfo.getFilePath()), Fragment1.this.getContext());
            }

            @Override // com.zzj.filedownloader.download.DownLoadListener
            public void onError(SQLDownLoadInfo sQLDownLoadInfo) {
                Logger logger = Logger.getLogger();
                logger.d("onError,name=" + sQLDownLoadInfo.getTaskID());
                Button button = Fragment1.this.mViewHolderArray.get(sQLDownLoadInfo.getTaskID().hashCode());
                if (button != null) {
                    button.setText("暂停");
                }
            }
        }

        /* loaded from: classes.dex */
        class Holder {
            ImageView aapIcon;
            TextView appName = null;
            TextView localVersion = null;
            TextView remoteVersion;
            Button update_btn;

            Holder() {
            }
        }
    }

    public void installApp(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(C.ENCODING_PCM_MU_LAW);
        Logger logger = Logger.getLogger();
        logger.d("file=" + file.getAbsolutePath());
        intent.setAction("android.intent.action.VIEW");
        if (Build.VERSION.SDK_INT >= 24) {
            Uri uriForFile = FileProvider.getUriForFile(context, "com.jxw.launcher.fileprovider", file);
            intent.addFlags(1);
            intent.setDataAndType(uriForFile, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
